var Card = require('./card').Card;
var MAX_PLAYER_CARD = 15;

function CardContainer(){
    this.cards = new Array(MAX_PLAYER_CARD);
    this.card_num = 0;
}

CardContainer.prototype.getCardNum = function() {return this.card_num;};

CardContainer.prototype.getCards = function(){
    var ret = [];
    for(var i = 0;i < this.cards.length;++i){
        if(this.cards[i]){
            ret.push(this.cards[i]);
        }
    }
    return ret;
}
CardContainer.prototype.playCard = function(cards_index){
    var cards = [];
    for(var i = 0;i < cards_index.length; i++){
        cards.push(this.cards[cards_index[i]]);
        this.cards[cards_index[i]] = undefined;
        --this.card_num;
    }
    return cards;
};

CardContainer.prototype.dropCard = function(cards_index){
    var cards = [];
    for(var i = 0;i < cards_index.length; i++){
        cards.push(this.cards(cards_index[i]));
        this.cards[cards_index[i]] = undefined;
        --this.card_num;
    }
    return cards;
}

CardContainer.prototype.drawCard = function(num,candicates,cards){
    if(this.getCardNum() + num > MAX_PLAYER_CARD){
        return false;
    }
    var base = 0;
    for(var card in candicates){
        if(candicates.hasOwnProperty(card)){
            base += app.getConfig().cards[card].prob;
        }
    }
    var i = 0;
    while(i < num){
        i++;
        var card_index = 0;
        for(card_index = 0; card_index < MAX_PLAYER_CARD; ++card_index){
            //choose an empty card position to insert
            if(!this.cards[card_index]){
                break;
            }
        }
        var random_factor = Math.floor(Math.random() * (base + 1));
        for(var card in candicates){
            if(!candicates.hasOwnProperty(card)){
                continue;
            }
            var factor = app.getConfig().cards[card].prob;
            //choose this card
            if(random_factor < factor){
                //attack card
                var params ={};
                if(card == "attack"){
                    params["num"] = Math.floor(Math.random() * 9) + 1;
                }else{
                    params = app.getConfig().cards[card].params;
                }
                this.cards[card_index] = Card.createCardByName(card,params);
                ++this.card_num;
                cards.push(this.cards[card_index]);
                break;
            }else{
                random_factor -= factor;
            }
        }
    }
    return true;
};

module.exports = CardContainer;